﻿using System;
using curbside.Core.Utility.Serialize;

namespace curbside.Web.UI.WebControls
{
    /// <summary>
    /// 重写TextBox
    /// </summary>
    public class TextBox : System.Web.UI.WebControls.TextBox
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (Autocomplete) this.Attributes.Add("autocomplete", "off");
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            base.Render(writer);
            string jsEvent = "$(function(){var jtxt = $('#" + this.ClientID + "');";

            string jsCode = string.Empty;

            if (!string.IsNullOrEmpty(DefaultValue))
            {
                jsCode += "jtxt.memo({"
                    + "defaultValue:\"" + DefaultValue + "\""
                    + "});";
                jsCode += "jtxt.blur();";
            }

            if (Autocomplete)
            {
                jsCode += "jtxt.autocomplete({"
                    + "source:" + SerializeHelper.JsonSerialize(DataSource) + ","
                    + "minLength:" + AutoMinLength
                    + "})";
            }

            if (!string.IsNullOrEmpty(jsCode))
            {
                jsEvent += jsCode + "});";
                helper.AddStartupScript(ClientID, jsEvent, this.Page);
            }
        }

        /// <summary>
        /// 设置或获取 具有memo效果的默认值
        /// </summary>
        public string DefaultValue
        {
            get
            {
                string str = this.ViewState["DefaultValue"] as string;
                if (str != null) return str;
                return string.Empty;
            }
            set { this.ViewState["DefaultValue"] = value; }
        }

        /// <summary>
        /// 设置或获取 是否自动提示
        /// </summary>
        public bool Autocomplete
        {
            get
            {
                object obj = this.ViewState["Autocomplete"];
                if (obj == null) return false;
                return (bool)obj;
            }
            set { this.ViewState["Autocomplete"] = value; }
        }

        /// <summary>
        /// 设置或获取 触发自动提示的输入字符长度
        /// 默认值为1
        /// </summary>
        public int AutoMinLength
        {
            get
            {
                object obj = this.ViewState["AutoMinLength"];
                if (obj == null) return 1;
                return (int)obj;
            }
            set { this.ViewState["AutoMinLength"] = value; }
        }

        /// <summary>
        /// 设置或获取 自动提示数据源
        /// </summary>
        public string[] DataSource
        {
            get { return this.ViewState["DataSource"] as string[]; }
            set { this.ViewState["DataSource"] = value; }
        }
    }
}
